﻿
using System;
using System.Net;
using System.Collections.Generic;

namespace LExperiment.NetworkLib
{
    public static class NetworkUtility
    {
        public static byte[] CombineHeaderBody(PacketHeader header, byte[] body)
        {
            header.BodyLength = body.Length;

            byte[] wholeBinImage = new byte[PacketHeader.HeaderLength + body.Length];
            Buffer.BlockCopy(header.BinaryImage, 0, wholeBinImage, 0, PacketHeader.HeaderLength);
            Buffer.BlockCopy(body, 0, wholeBinImage, PacketHeader.HeaderLength, body.Length);

            return wholeBinImage;
        }

        public static IPEndPoint CreateEndPoint(string hostNameOrAddress, int port)
        {
            if (string.IsNullOrEmpty(hostNameOrAddress))
            {
                return new IPEndPoint(IPAddress.Any, port);
            }
            else
            {
                IPAddress address;
                if (IPAddress.TryParse(hostNameOrAddress, out address))
                    // Use the provided IP address.
                    return new IPEndPoint(address, port);
                else
                    // Exception will occur if DNS lookup fails.
                    return new IPEndPoint(Dns.GetHostEntry(hostNameOrAddress).AddressList[0], port);
            }
        }
    }

    public static class BufferUtility
    {
        //------------------------------------------------------//
        #region [ ushort ]

        public static void CopyBytes(ushort value, byte[] destinationArray, int destinationIndex)
        {
            Buffer.BlockCopy(BitConverter.GetBytes(value), 0, destinationArray, destinationIndex, 2);
        }

        public static ushort ToUInt16(byte[] value, int startIndex)
        {
            byte[] buffer = new byte[2];

            Buffer.BlockCopy(value, startIndex, buffer, 0, 2);

            return BitConverter.ToUInt16(buffer, 0);
        }

        #endregion

        //------------------------------------------------------//
        #region [ int32 ]

        public static void CopyBytes(int value, byte[] destinationArray, int destinationIndex)
        {
            Buffer.BlockCopy(BitConverter.GetBytes(value), 0, destinationArray, destinationIndex, 4);
        }

        public static int ToInt32(byte[] value, int startIndex)
        {
            byte[] buffer = new byte[4];

            Buffer.BlockCopy(value, startIndex, buffer, 0, 4);

            return BitConverter.ToInt32(buffer, 0);
        }

        #endregion
    }
}